package com.gitee.mazhenggg.demo.log.service;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;

public class server {
        public static final String SERVICE_IP = "127.0.0.1";

        public static final int SERVICE_PORT = 9000;

        public static void main(String[] args) {
            server service = new server();
            //启动服务端
            service.startService(SERVICE_IP,SERVICE_PORT);
        }

        private void startService(String serverIP, int serverPort){
            try {
                //封装服务端地址
                InetAddress serverAddress = InetAddress.getByName(serverIP);
                //建立服务端
                try(ServerSocket service = new ServerSocket(serverPort, 10, serverAddress)){
                    while (true) {
                        //接受一个连接，该方法会阻塞程序，直到一个链接到来
                        try(Socket connect = service.accept()){
                            //获得输入流
                            InputStream in = connect.getInputStream();
                            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                            BufferedWriter bw  = new BufferedWriter(new OutputStreamWriter(connect.getOutputStream()));

                            String line;
                            while((line=br.readLine())!=null){
                                System.out.println("line:"+line);
                                bw.write(line);
                                bw.flush();
                            }


                        }catch (Exception e){
                            e.printStackTrace();
                        }
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }
            } catch (UnknownHostException e) {
                e.printStackTrace();
            }
        }

}
